package sapling.logic.algorithm.pcb.queue;

import sapling.logic.object.pcb.ProcessControlBlock;

public class PriorityQueue extends Queue {
	@Override
	public boolean enqueue(ProcessControlBlock proc) {
		Node<ProcessControlBlock> temp = this.head;
		while (temp.getNext() != null && temp.getNext().getData().getPriority() >= proc.getPriority()) {
			temp = temp.getNext();
		}
		temp.setNext(new Node<ProcessControlBlock>(temp, proc, temp.getNext()));
		if (temp.getNext().getNext() != null)
			temp.getNext().getNext().setPrev(temp.getNext());
		this.length++;
		return false;

	}

	public void upPriority(Node<ProcessControlBlock> p, int i) {
		p.getData().setPriority(p.getData().getPriority() + i);
		while (!p.getPrev().isHead() && p.getData().getPriority() > p.getPrev().getData().getPriority()) {
			if (p.getNext() != null)
				p.getNext().setPrev(p.getPrev());
			p.getPrev().setNext(p.getNext());
			p.setPrev(p.getPrev().getPrev());
			p.setNext(p.getPrev().getNext());
			p.getPrev().setNext(p);
			p.getNext().setPrev(p);
		}
	}

	@Override
	public ProcessControlBlock dequeue() {
		return this.remove(0);
	}

	@Override
	public ProcessControlBlock peek() {
		return this.get(0);
	}
}
